#! /usr/bin/env python
#coding=utf-8

# pylint: disable-msg=W0704

#! /usr/bin/env python
#coding=utf-8

# pylint: disable-msg=W0704
import os
import jenkins
import re

########################################## JENKINS
JENKINS_URL = 'http://xxx.16.3.xx:1111/'
JENKINS_USERNAME = 'xxx'
JENKINS_PASSWORD = 'xxxxx'

TEMPLATE_GIT_PACKAGE = "TEMPLATE_GIT_PACKAGE"

# 针对url中存在中文时候
import sys
reload(sys)
sys.setdefaultencoding('utf8')

def run(transaction, config):
  # 只针对特定的project进行处理
  if not "xxxx/trans" in os.getenv("GL_PROJECT_PATH"):
    return("", 0)

  commitMsg = transaction.getCommitMsgWithLinesep()  # getCommitMsg
  userId = transaction.getUserID()
  reversion = transaction.getRevision()

  commitMsgBylines = commitMsg.splitlines(False)
  needCICD = False
  result = None

  for msgLine in commitMsgBylines:
    patt = re.compile("^#CICD\:\s(jjb|package)")
    result = re.search(patt, msgLine)
    if(result != None):
      needCICD = True
      break

  if not needCICD:
    return ("no need CICD", 0)

  operateType = result.group(1)

  # 筛选出下载地址要推送到的禅道位置
  firstLine = commitMsgBylines[0].strip()
  patt = re.compile("(story|bug|task)\:(\d+)\s.+")
  result = re.search(patt,firstLine)
  if(result == None):
    return("自动打包-不包含要推送到zentao地址", 0)

  objecType = result.group(1)
  objectID = result.group(2)


  ##### 筛选出本次需要进行的 CICD 操作
  if operateType == "jjb":
    # 创建任务
    pass
  elif operateType == "package":
    # 执行jenkinsfile: 打包, 推送到制品库, 将下载链接反写到zentao
    return _package(os.getenv("GL_PROJECT_PATH"), {"ZENTAO_OBJECT_TYPE": objecType, "ZENTAO_OBJECT_ID": objectID, "ZENTAO_ACTOR" : userId  })
  else:
    return ("unkown operaType: " + operateType, 0)



def _package(gitUrl, params):
  # http://xxxx:9527/joint3.0/trans/xxx-trans-xx-weifang-xxx.git
  # gitUrl : joint3.0/trans/xxx-trans-xx-weifang-xxx
  # jjName : xxx-trans-xx-weifang-xxx
  jjbName = gitUrl.split("/")[-1].split(".")[0]
  jjbName = "dj_" + jjbName
  if not _jenkins_job_exist(jjbName):
    _jjb(jjbName, "http://root:XXX@172.16.3.xx:1111/" + gitUrl + ".git")

  if not _jenkins_job_exist(jjbName):
    return ("jjb失败", 1)

  print("begin package-auto")
  server = _getServer()
  server.build_job(jjbName, params)
  return ("", 0)


def _jjb(jjbName, gitUrl):
  server = _getServer()

  templateOfGitPackage = server.get_job_config(TEMPLATE_GIT_PACKAGE)
  templateOfGitPackage = str(templateOfGitPackage).replace("{{GIT_URL}}", gitUrl)
  server.create_job(jjbName, templateOfGitPackage)

def _jenkins_job_exist(jjbName):
  server = _getServer()
  try:
      server.get_job_config(jjbName)
  except(jenkins.NotFoundException) as ex:
      return False

  return True

def _getServer():
  return jenkins.Jenkins(JENKINS_URL, username=JENKINS_USERNAME, password=JENKINS_PASSWORD)